package com.yuzhitong.shapi.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.bytedance.sdk.dp.DPArticleLevel;
import com.bytedance.sdk.dp.DPComponentPosition;
import com.bytedance.sdk.dp.DPSdk;
import com.bytedance.sdk.dp.DPWidgetTextChainParams;
import com.bytedance.sdk.dp.DPWidgetVideoCardParams;
import com.bytedance.sdk.dp.IDPAdListener;
import com.bytedance.sdk.dp.IDPElement;
import com.bytedance.sdk.dp.IDPTextChainListener;
import com.bytedance.sdk.dp.IDPVideoCardListener;
import com.bytedance.sdk.dp.IDPWidgetFactory;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.activity.CategoryActivity;
import a.a.a.MyApplication;

import com.yuzhitong.shapi.activity.PlayNewActivity;
import com.yuzhitong.shapi.base.BaseMvpFragment;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.base.recycler.BaseAdapter;
import com.yuzhitong.shapi.base.recycler.BaseItemsAdapter;
import com.yuzhitong.shapi.base.recycler.BaseViewHolder;
import com.yuzhitong.shapi.bean.MovieBean;
import com.yuzhitong.shapi.bean.MovieOnlyBean;
import com.yuzhitong.shapi.contract.MovieListContract;
import com.yuzhitong.shapi.presenter.MovieListPresenter;
import com.yuzhitong.shapi.util.AdUtilManage;
import com.yuzhitong.shapi.util.GlideUtil;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.StringUtil;
import com.yuzhitong.shapi.util.UiUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Brsya
 * CreateDate: 2022/5/8  15:57
 * Description:
 * 影视列表
 */
public class MovieListOnlyFragment extends BaseMvpFragment<MovieListPresenter> implements MovieListContract.View {

    private RecyclerView rvSearchMovieList;

    private View rlAdText;
    private View rlAdVideo;
    private View rlAdImg;


    private BaseItemsAdapter<MovieOnlyBean> adapter;
    private BaseAdapter<MovieBean> hotAdapter;

    // 改变上层搜索框文字
    private MovieListFragment.OnSearchTextChange onSearchTextChange;

    // 类型
    private String pageType;
    // 排序
    private String pageSort;

    // 广告管理类
    private AdUtilManage adUtilManage;

    private boolean firstLoad;

    private boolean isPreload;

    private List<MovieBean> dayList;

    public static MovieListOnlyFragment newInstance(String type, String sort) {

        Bundle args = new Bundle();
        args.putString("type", type);
        args.putString("sort", sort);

        MovieListOnlyFragment fragment = new MovieListOnlyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static MovieListOnlyFragment newInstance(String type, String sort, boolean isPreload) {

        Bundle args = new Bundle();
        args.putString("type", type);
        args.putString("sort", sort);
        args.putBoolean("isPreload", isPreload);

        MovieListOnlyFragment fragment = new MovieListOnlyFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_search_movie);
        rvSearchMovieList = findViewById(R.id.rv_search_movie_list);
    }

    @Override
    protected void initData() {
        if (getArguments() != null) {
            pageType = getArguments().getString("type");
            pageSort = getArguments().getString("sort");
            isPreload = getArguments().getBoolean("isPreload", false);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int itemViewType = adapter.getItemViewType(position);
                switch (itemViewType) {
                    default:
                    case MovieOnlyBean.TYPE_TITLE:
                    case MovieOnlyBean.TYPE_HOT_LIST:
                    case MovieOnlyBean.TYPE_AD_TEXT:
                    case MovieOnlyBean.TYPE_AD_VIDEO:
                    case MovieOnlyBean.TYPE_AD_IMG:
                        return 3;
                    case MovieOnlyBean.TYPE_DAY:
                        return 1;
                }
            }
        });
        rvSearchMovieList.setLayoutManager(gridLayoutManager);
        rvSearchMovieList.setAdapter(adapter = new BaseItemsAdapter<MovieOnlyBean>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View rootView;
                LayoutInflater from = LayoutInflater.from(getContext());
                switch (viewType) {
                    default:
                    case MovieOnlyBean.TYPE_TITLE:
                        rootView = from.inflate(R.layout.item_only_movie_title, parent, false);
                        break;
                    case MovieOnlyBean.TYPE_HOT_LIST:
                        rootView = from.inflate(R.layout.item_only_movie_h_recycle, parent, false);
                        break;
                    case MovieOnlyBean.TYPE_AD_TEXT:
                        rootView = from.inflate(R.layout.item_only_movie_ad_text, parent, false);
                        break;
                    case MovieOnlyBean.TYPE_AD_VIDEO:
                        rootView = from.inflate(R.layout.item_only_movie_ad_video, parent, false);
                        break;
                    case MovieOnlyBean.TYPE_AD_IMG:
                        rootView = from.inflate(R.layout.item_only_movie_ad_img, parent, false);
                        break;
                    case MovieOnlyBean.TYPE_DAY:
                        rootView = from.inflate(R.layout.item_movie, parent, false);
                        break;
                }
                return new BaseViewHolder(rootView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieOnlyBean data) {
                int type = data.getType();
                switch (type) {
                    default:
                        break;
                    case MovieOnlyBean.TYPE_TITLE:
                        TextView tvSortTitle = viewHolder.findViewById(R.id.tv_sort_title);
                        TextView tvShowMore = viewHolder.findViewById(R.id.tv_show_more);
                        tvSortTitle.setText(data.getTitle());
                        tvShowMore.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), CategoryActivity.class);
                                intent.putExtra(Contents.INTENT_MOVIE_TYPE, pageType);
                                if (data.isHot()) {
                                    intent.putExtra(Contents.INTENT_MOVIE_SORT, pageSort);
                                }
                                startActivity(intent);
                            }
                        });
                        break;
                    case MovieOnlyBean.TYPE_HOT_LIST:
                        RecyclerView rvHList = viewHolder.findViewById(R.id.rv_movie_list);
                        if (hotAdapter == null) {
                            hotAdapter = new BaseAdapter<MovieBean>() {
                                @Override
                                public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                                    View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_movie_line, parent, false);
                                    return new BaseViewHolder(itemView);
                                }

                                @Override
                                public void onBind(BaseViewHolder dayHotHolder, int RealPosition, MovieBean data) {
                                    ImageView ivMovieImg = dayHotHolder.findViewById(R.id.iv_movie_img);
                                    TextView tvMovieTitle = dayHotHolder.findViewById(R.id.tv_movie_title);
                                    dayHotHolder.findViewById(R.id.sv_score_box).setVisibility(View.GONE);

                                    tvMovieTitle.setText(data.getName());
                                    GlideUtil.loadRound(ivMovieImg, data.getCoverUrl(), 4);
                                }
                            };
                            hotAdapter.setOnItemClickListener((position, movieBean) -> {
                                Intent intent = new Intent(getActivity(), PlayNewActivity.class);
                                intent.putExtra(Contents.INTENT_MOVIE_DETAIL, movieBean);
                                startActivity(intent);
                            });
                            hotAdapter.setDataList(data.getMovieBeans());
                        }
                        rvHList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
                        rvHList.setAdapter(hotAdapter);
                        break;
                    case MovieOnlyBean.TYPE_AD_TEXT:
                        RelativeLayout rlMovieAdText = viewHolder.findViewById(R.id.rl_movie_ad_text);
                        if (rlAdText == null || rlMovieAdText.getChildCount() == 0) {
                            getText(rlMovieAdText);
                        }
                        break;
                    case MovieOnlyBean.TYPE_AD_VIDEO:
                        RelativeLayout rlMovieAdVideo = viewHolder.findViewById(R.id.rl_movie_ad_video);
                        if (rlAdVideo == null || rlMovieAdVideo.getChildCount() == 0) {
                            getVideo(rlMovieAdVideo);
                        }
                        break;
                    case MovieOnlyBean.TYPE_AD_IMG:
                        RelativeLayout flAdBox = viewHolder.findViewById(R.id.fl_ad_box);
                        if (rlAdVideo == null || flAdBox.getChildCount() == 0) {
                            getImg(flAdBox);
                        }
                        break;
                    case MovieOnlyBean.TYPE_DAY:
                        ImageView ivMovieImg = viewHolder.findViewById(R.id.iv_movie_img);
                        TextView tvMovieTitle = viewHolder.findViewById(R.id.tv_movie_title);
                        viewHolder.findViewById(R.id.sv_score_box).setVisibility(View.GONE);

                        tvMovieTitle.setText(data.getMovieBean().getName());
                        GlideUtil.loadRound(ivMovieImg, data.getMovieBean().getCoverUrl(), 4);
                        break;
                }
            }

            @Override
            public int getLayoutType(int RealPosition) {
                return adapter.getDataList().get(RealPosition).getType();
            }
        });


        adapter.setOnItemClickListener((position, data) -> {
            if (data.getType() != MovieOnlyBean.TYPE_DAY) {
                return;
            }
            Intent intent = new Intent(getActivity(), PlayNewActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_DETAIL, data.getMovieBean());
            startActivity(intent);
        });

        if (isPreload) {
            try {
                String day = MyApplication.aCache.getAsString(Contents.CACHE_KEY_CATEGORY_DAY);
                if (!StringUtil.isEmpty(day)) {
                    dayList = JSON.parseArray(day, MovieBean.class);
                } else {
                    LoggerUtil.e("今日数据为空");
                }
                String hot = MyApplication.aCache.getAsString(Contents.CACHE_KEY_CATEGORY_HOT);
                if (!StringUtil.isEmpty(hot)) {
                    List<MovieBean> list = JSON.parseArray(hot, MovieBean.class);
                    showHot(list);
                } else {
                    LoggerUtil.e("热门数据为空");
                }
            } catch (Exception e) {
                // 解析失败不做处理,继续请求网络数据
                isPreload = false;
            }
        }
        if (!isPreload) {
            loadData();
        } else {
            isPreload = false;
        }
    }


    private void getImg(RelativeLayout flAdBox) {
        if (rlAdImg != null) {
            if (rlAdImg.getParent() != null) {
                if (rlAdImg.getParent() instanceof ViewGroup) {
                    ((ViewGroup) rlAdImg.getParent()).removeAllViews();
                }
            }
            flAdBox.addView(rlAdImg);
            return;
        }
        // 加载图文广告
        initShow(getActivity(), flAdBox, Contents.AD_TT_SDK_SETTING_ID);

    }

    public void initShow(Activity context, ViewGroup viewGroup, String adId) {

        if (!MyApplication.isOpenAd()) {
            return;
        }

        float xdpi = context.getResources().getDisplayMetrics().xdpi;

        // 加载广告
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(context);

        AdSlot adSlot = new AdSlot.Builder()
                // 广告ID 948498437 948498604
                .setCodeId(adId)
                .setSupportDeepLink(true)
                .setAdCount(1)
                // 期望模板广告view的size,单位dp
                .setExpressViewAcceptedSize(xdpi, 0)
                .setAdloadSeq(1)
                .build();

        viewGroup.removeAllViews();
        adNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int i, String s) {
                LoggerUtil.i("穿山甲广告加载失败" + i + "--ss--" + s);
                viewGroup.setVisibility(View.GONE);
                List<MovieOnlyBean> dataList = new LinkedList<>(adapter.getDataList());
                for (MovieOnlyBean movieOnlyBean : dataList) {
                    if (movieOnlyBean.getType() == MovieOnlyBean.TYPE_AD_IMG) {
                        dataList.remove(movieOnlyBean);
                        break;
                    }
                }
                adapter.setDataList(dataList);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                LoggerUtil.e("广告加载成功");
                viewGroup.setVisibility(View.VISIBLE);
                for (TTNativeExpressAd adBean : list) {
                    viewGroup.removeAllViews();
                    View adRootView = adBean.getExpressAdView();
                    rlAdImg = adRootView;
                    // 无法居中
                    //                    if (adRootView instanceof FrameLayout){
                    //                        FrameLayout fl = (FrameLayout) adRootView;
                    //                        for (int i = 0; i < fl.getChildCount(); i++) {
                    //                            if (!(fl.getChildAt(i) instanceof ViewGroup)){
                    //                                continue;
                    //                            }
                    //                            if (((ViewGroup) fl.getChildAt(i)).getChildCount() > 0){
                    //                                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) fl.getChildAt(i).getLayoutParams();
                    //                                layoutParams.gravity = Gravity.CENTER;
                    //                                fl.setLayoutParams(layoutParams);
                    //                            }
                    //                        }
                    //                    }
                    viewGroup.addView(adRootView);
                    adBean.render();
                    adBean.setDislikeCallback(context, new TTAdDislike.DislikeInteractionCallback() {
                        @Override
                        public void onShow() {
                            if (viewGroup != null) {
                                viewGroup.removeAllViews();
                                viewGroup.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onSelected(int i, String s, boolean b) {

                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                    break;
                }
            }
        });
    }


    private void getVideo(RelativeLayout rlMovieAdVideo) {

        if (rlAdVideo != null) {
            if (rlAdVideo.getParent() != null) {
                if (rlAdVideo.getParent() instanceof ViewGroup) {
                    ((ViewGroup) rlAdVideo.getParent()).removeAllViews();
                }
            }
            rlMovieAdVideo.addView(rlAdVideo);
            return;
        }
        // 加载穿山甲小视频卡片
        DPSdk.factory().loadCustomVideoCard(
                DPWidgetVideoCardParams.obtain()
                        .cardHeight(134)
                        .listener(new IDPVideoCardListener() {
                            @Override
                            public void onDPItemClick(Map<String, Object> map) {
                                super.onDPItemClick(map);
                                //                                if (getActivity() != null) {
                                //                                    getActivity().getWindow().setNavigationBarColor(0xFF000000);
                                //                                }
                            }

                            @Override
                            public void onDPLSwipeEnter() {
                                super.onDPLSwipeEnter();
                                //                                if (getActivity() != null) {
                                //                                    getActivity().getWindow().setNavigationBarColor(0xFF000000);
                                //                                }
                            }
                        })
                        .adListener(new IDPAdListener() {

                        })
                        .dislikeListener(getActivity(), s -> LoggerUtil.e("小视频onSelected: " + s))
                , new IDPWidgetFactory.Callback() {

                    @Override
                    public void onError(int i, String s) {
                        LoggerUtil.e("小视频加载失败: " + i + " --- " + s);
                    }

                    @Override
                    public void onSuccess(IDPElement idpElement) {
                        rlAdVideo = idpElement.getView();
                        if (rlAdVideo == null || rlMovieAdVideo == null) {
                            return;
                        }
                        rlMovieAdVideo.removeAllViews();
                        rlMovieAdVideo.setVisibility(View.VISIBLE);
                        ViewGroup viewGroup = (ViewGroup) rlAdVideo.getParent();
                        if (viewGroup != null) {
                            viewGroup.removeAllViews();
                        }
                        rlMovieAdVideo.addView(rlAdVideo);
                    }
                });
    }

    private void getText(RelativeLayout rlMovieAdText) {
        if (rlAdText != null) {
            if (rlAdText.getParent() != null) {
                if (rlAdText.getParent() instanceof ViewGroup) {
                    ((ViewGroup) rlAdText.getParent()).removeAllViews();
                }
            }
            rlMovieAdText.addView(rlAdText);
            return;
        }
        // 加载穿山甲气泡
        DPSdk.factory().loadTextChain(
                DPWidgetTextChainParams.obtain()
                        .articleLevel(DPArticleLevel.LEVEL_2) // 内容等级
                        .componentPosition(DPComponentPosition.TAB2)
                        .animationDuration(300) // 动画时长
                        //                        .backgroundColor(0xFFE7F6FF)// 背景颜色
                        .iconDrawable(ResourcesCompat.getDrawable(getResources(), R.mipmap.icon_movie_home_hot, null))
                        .iconWidth(15)
                        .iconHeight(17)
                        .showDuration(4000) // 停留时长
                        .showWatch(true) // 是否展示观看信息
                        //                        .titleTextColor(0x880560D1) // 标题文字颜色
                        .titleTextSize(16) // 标题文字大小
                        //                        .watchTextColor(0x880560D1) // 观看文字颜色
                        .watchTextSize(16) // 观看文字大小
                        .listener(new IDPTextChainListener() {})
                        .adListener(new IDPAdListener() {})

                , new IDPWidgetFactory.Callback() {
                    @Override
                    public void onError(int i, String s) {
                        LoggerUtil.e("气泡加载失败: " + i + " --- " + s);
                    }

                    @Override
                    public void onSuccess(IDPElement idpElement) {
                        rlAdText = idpElement.getView();
                        if (rlAdText == null || rlMovieAdText == null) {
                            return;
                        }
                        rlMovieAdText.removeAllViews();
                        rlMovieAdText.setVisibility(View.VISIBLE);
                        ViewGroup viewGroup = (ViewGroup) rlAdText.getParent();
                        if (viewGroup != null) {
                            viewGroup.removeAllViews();
                        }
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                                RelativeLayout.LayoutParams.MATCH_PARENT
                                , UiUtil.dpToPx(Objects.requireNonNull(getActivity()), 32));
                        rlAdText.setLayoutParams(lp);
                        rlMovieAdText.addView(rlAdText);

                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            getActivity().getWindow().setNavigationBarColor(0xFFFFFFFF);
        }
//        if (!firstLoad) {
//            firstLoad = true;
//            loadData();
//        }
    }

    private void loadData() {
        if (isPreload) {
            isPreload = false;
            return;
        }
        presenter.getHot(pageType, pageSort);
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AdUtilManage.destroy(adUtilManage);
    }

    @Override
    protected void initPresenter() {
        presenter = new MovieListPresenter();
        presenter.attachView(this);
    }

    @Override
    public void showHot(List<MovieBean> categoryBeans) {
        if (onSearchTextChange != null) {
            if (categoryBeans != null && categoryBeans.size() > 0) {
                onSearchTextChange.changeSearchText(categoryBeans.get(0).getName());
            }
        }

        List<MovieOnlyBean> dataList = new ArrayList<>();

        // 标题
        MovieOnlyBean titleBean = new MovieOnlyBean();
        titleBean.setType(MovieOnlyBean.TYPE_TITLE);
        titleBean.setHot(true);
        titleBean.setTitle(pageSort);
        dataList.add(titleBean);

        // 热门列表 - 横向列表
        MovieOnlyBean hotListBean = new MovieOnlyBean();
        hotListBean.setType(MovieOnlyBean.TYPE_HOT_LIST);
        hotListBean.setMovieBeans(categoryBeans);
        dataList.add(hotListBean);

        // 文字气泡广告
        MovieOnlyBean adTextBean = new MovieOnlyBean();
        adTextBean.setType(MovieOnlyBean.TYPE_AD_TEXT);
        dataList.add(adTextBean);

        // 精彩小食品广告
        MovieOnlyBean adVideoBean = new MovieOnlyBean();
        adVideoBean.setType(MovieOnlyBean.TYPE_AD_VIDEO);
        dataList.add(adVideoBean);

        adapter.setDataList(dataList);
        adapter.notifyDataSetChanged();
        if (!isPreload) {
            presenter.getDayHot(1, pageType);
        } else {
            if (dayList != null) {
                showDayHot(dayList);
            }
        }
    }

    @Override
    public void showDayHot(List<MovieBean> categoryBeans) {
        if (categoryBeans == null) {
            return;
        }

        List<MovieOnlyBean> dataList = new ArrayList<>();
        dataList.addAll(adapter.getDataList());

        // 标题
        MovieOnlyBean titleBean = new MovieOnlyBean();
        titleBean.setType(MovieOnlyBean.TYPE_TITLE);
        titleBean.setHot(false);
        titleBean.setTitle("今日推荐");
        dataList.add(titleBean);

        for (int i = 0; i < categoryBeans.size(); i++) {
            if (i >= 6) {
                break;
            }
            // 今日推荐数据
            MovieOnlyBean movieBean = new MovieOnlyBean();
            movieBean.setType(MovieOnlyBean.TYPE_DAY);
            movieBean.setMovieBean(categoryBeans.get(i));
            dataList.add(movieBean);
        }

        // 图文广告
        MovieOnlyBean adVideoBean = new MovieOnlyBean();
        adVideoBean.setType(MovieOnlyBean.TYPE_AD_IMG);
        dataList.add(adVideoBean);

        if (categoryBeans.size() <= 6) {
            return;
        }

        for (int i = 6; i < categoryBeans.size(); i++) {
            // 今日推荐数据
            MovieOnlyBean movieBean = new MovieOnlyBean();
            movieBean.setType(MovieOnlyBean.TYPE_DAY);
            movieBean.setMovieBean(categoryBeans.get(i));
            dataList.add(movieBean);
        }

        adapter.setDataList(dataList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showNoMore() {
    }

    public void setOnSearchTextChange(MovieListFragment.OnSearchTextChange onSearchTextChange) {
        this.onSearchTextChange = onSearchTextChange;
    }

    public interface OnSearchTextChange {
        void changeSearchText(String text);
    }
}
